/*
 * Copyright (c) 2018-2999 北京国电高科科技有限公司 All rights reserved.
 *
 * https://www.tqmall.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.gdgk.shop.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gdgk.shop.bean.app.dto.UserDto;
import com.gdgk.shop.bean.app.param.UserInfoParam;
import com.gdgk.shop.bean.app.param.UserMobileBindParam;
import com.gdgk.shop.bean.model.User;
import com.gdgk.shop.common.constants.SmsCacheNames;
import com.gdgk.shop.common.exception.GdgkShopBindException;
import com.gdgk.shop.common.util.RedisUtil;
import com.gdgk.shop.dao.UserMapper;
import com.gdgk.shop.security.api.util.SecurityUtils;
import com.gdgk.shop.service.ScoreService;
import com.gdgk.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import com.gdgk.shop.common.response.ServerResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.Wrapper;

/**
 * @author lanhai
 */
@RestController
@RequestMapping("/p/user")
@Tag(name = "用户接口")
@AllArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;

    private final UserMapper userMapper;

    private final ScoreService scoreService;

    /**
     * 查看用户接口
     */
    @GetMapping("/userInfo")
    @Operation(summary = "查看用户信息", description = "根据用户ID（userId）获取用户信息")
    public ServerResponseEntity<UserDto> userInfo() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        UserDto userDto = BeanUtil.copyProperties(user, UserDto.class);
        return ServerResponseEntity.success(userDto);
    }

    @PutMapping("/setUserInfo")
    @Operation(summary = "设置用户信息", description = "设置用户信息")
    public ServerResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = new User();
        user.setUserId(userId);
        user.setPic(userInfoParam.getAvatarUrl());
        user.setNickName(userInfoParam.getNickName());
        userService.updateById(user);
        return ServerResponseEntity.success();
    }


    @PostMapping("/queryScore")
    public ServerResponseEntity<User> queryScoreByMobileNumber(@RequestParam("mobileNumber") String mobileNumber) {
        if (StringUtils.isBlank(mobileNumber) && mobileNumber.length() != 11) {
            // 返回手机号格式错误
            log.info("查询的用户手机号码格式异常! ");
            return ServerResponseEntity.showFailMsg("查询的用户手机号码格式异常! ");
        }
        try {
            User user = new User();
            user.setScore(scoreService.queryScoreByMobileNumber(mobileNumber));
            return ServerResponseEntity.success(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/bindUserMobile")
    @Operation(summary = "手机号绑定", description = "手机号绑定")
    @Transactional
    public ServerResponseEntity<Void> bindUserMobile(@RequestBody UserMobileBindParam userMobileBindParam) throws Exception {
        String userMobile = userMobileBindParam.getUserMobile();
        String validCode = userMobileBindParam.getValidCode();
        String userId = SecurityUtils.getUser().getUserId();
        String cacheValidCode = RedisUtil.get(SmsCacheNames.USER_VALID_CODE_PREFIX + userId);
        User userQueryByMobile = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserMobile, userMobile));

        if (cacheValidCode == null) {
            throw new GdgkShopBindException("您的验证码已过期!");
        }
        if (!cacheValidCode.equals(validCode)) {
            throw new GdgkShopBindException("您的验证码错误!");
        }
        if (userQueryByMobile != null) {
            throw new GdgkShopBindException("该手机号已绑定!");
        }
        User user = userService.getUserByUserId(userId);
        User userQueryByUserId = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserId, userId));
        if (userQueryByUserId == null) {
            throw new GdgkShopBindException("非法操作!");
        }
        userQueryByUserId.setUserMobile(userMobile);
        int bindMobile = userMapper.updateById(userQueryByUserId);
        if (bindMobile > 0) {
            boolean bindScore = scoreService.bindingScoreByMobile(userMobile, user.getOpenId());
            if (bindScore) {
                user.setBindStatus(1);
                userService.updateById(user);
                return ServerResponseEntity.success();
            } else {
                throw new GdgkShopBindException("您无积分发放记录，绑定手机号失败!");
            }
        } else {
            return ServerResponseEntity.showFailMsg("绑定手机号失败!");
        }

    }
}
